﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.IO;
using System.Xml;


namespace DACK_MHTTUD_0912008_0912493
{
    class clsRSA
    {
        static public byte[] RSAEncrypt(byte[] DataToEncrypt, string path_privatekey_file, bool DoOAEPPadding)
        {
            try
            {
                Form1.publicAndPrivateKeys = "";
                Form1.justPublicKey = "";

                byte[] encryptedData;

                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    string str_xml = clsXML.GetStringXMLFromFile(path_privatekey_file);
                    RSA.FromXmlString(str_xml);
                    //Form1.publicAndPrivateKeys = RSA.ToXmlString(true);
                    //Form1.justPublicKey = RSA.ToXmlString(false);

                    encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
                }
                return encryptedData;
            }
            catch (CryptographicException e)
            {
                MessageBox.Show(e.Message);
                return null;
            }
        }

        static public byte[] RSADecrypt(byte[] DataToDecrypt, string path_publickey_file, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider. 
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    string str_xml = clsXML.GetStringXMLFromFile(path_publickey_file);
                    RSA.FromXmlString(str_xml);
                    decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
                }
                return decryptedData;
            }
            //Catch and display a CryptographicException   
            //to the console. 
            catch (CryptographicException e)
            {
                MessageBox.Show(e.Message);

                return null;
            }

        }
    }
}
